<template>
    <div class="app-container">
        <el-form :inline="true" @submit.native.prevent>
            <el-form-item label="项目名称:" prop="projectname">
                <el-input v-model="queryParams.projectname" placeholder="请输入项目名称" clearable size="small"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="showAdd(false)">新增</el-button>
          <el-button
            type="info"
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
          >导入</el-button>
          <el-button
            type="warning"
            icon="el-icon-position"
            size="mini"
            @click="handleExport"
          >导出</el-button>
        </el-form>

        <el-table :data="tableData" style="width: 100%" v-loading="loading">
            <el-table-column prop="projectname" label="项目名称"></el-table-column>
          <el-table-column label="是否信创" width="200" prop="isXC">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.isXc == true" type="danger" effect="plain">信创</el-tag>
              <el-tag v-else type="info" effect="plain">非信创</el-tag>
            </template>
          </el-table-column>
            <el-table-column prop="officeName" width="360" label="业务部门名称"> </el-table-column>
            <el-table-column width="260" prop="contactsNickName" label="业主方联系人"> </el-table-column>
            <el-table-column
                label="操作"
                class-name="small-padding fixed-width"
                width="160"
            >
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-view"
                        @click="showAdd(scope.row.id)"
                        >查看
                    </el-button>
                    <!-- <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="del(scope.row.id)"
                        >删除</el-button
                    > -->
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
        <el-dialog
        :title="loadingTitle"
        :visible.sync="ADDloading"
        width="80%">
            <div class="title">{{loadingTitle}}</div>
        <div class="msg">
            <el-form
                :model="cloudSystem"
                ref="cloudSystem"
                style="width: 100% !important"
                :rules="rules"
                label-width="120px"
                :disabled="loadingTitle != '新增项目'"
            >
                <div class="wrap" style="margin-top: 20px">
                    <div class="item">
                        <el-form-item label="应用系统名称:" prop="projectname">
                            <el-input
                                style="width: 200px"

                                placeholder="请输入系统名称"
                                v-model="cloudSystem.projectname"
                                clearable
                            >
                            </el-input>
                        </el-form-item>
                    </div>
                    <div class="item">
                        <el-form-item label="上线时间:" prop="onlinetime">
                            <el-date-picker
                                v-model="cloudSystem.onlinetime"
                                type="date"
                                style="width: 200px"
                                clearable
                                value-format="yyyy-MM-dd"
                                placeholder="请选择上线时间"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </div>
                    <div class="item">
                        <el-form-item label="等保:">
                            <el-select v-model="cloudSystem.protectLevel" placeholder="请选择"  style="width: 200px;">
                            <el-option v-for="item in available_domain" :key="item.dictValue" :label="item.dictLabel"
                                :value="item.dictValue">
                            </el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                    <el-form-item label="是否信创">
                        <el-radio-group v-model="cloudSystem.isXc">
                        <el-radio label="false">非信创</el-radio>
                        <el-radio label="true">信创</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <!-- <div class="item">
                        <el-form-item label="上云区域:">
                            <el-select clearable v-model="cloudSystem.cloudUpArea" placeholder="请选择"  style="width: 200px;">
                                <el-option v-for="item in cloud_up_areaList" :key="item.dictValue" :label="item.dictLabel"
                                    :value="item.dictValue">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </div> -->
                </div>
                <div class="wrap">
                    <div class="item">
                        <el-form-item label="业务部门:" prop="officeIdList">
                            <el-cascader
                                :props="{ value: 'id', checkStrictly: true }"
                                :show-all-levels="false"
                                @change="deptChange"
                                style="width: 200px"
                                v-model="cloudSystem.officeIdList"
                                placeholder="请选择，可搜索"
                                :options="dept"
                                clearable
                                filterable
                            ></el-cascader>
                        </el-form-item>
                    </div>
                    <div class="item">
                        <el-form-item label="业主方联系人:" prop="contacts">
                            <el-select
                                clearable
                                style="width: 200px"
                                v-model="cloudSystem.contacts"
                                :placeholder="
                                    cloudSystem.officeId
                                        ? '请选择业主方联系人'
                                        : '请先选择业务部门'
                                "
                            >
                                <el-option
                                    v-for="item in users"
                                    :key="item.userName"
                                    :label="item.nickName"
                                    :value="item.userName"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                    <div class="item">
                        <el-form-item label="联系电话:" prop="contactsinfo">
                            <el-input
                                style="width: 200px"

                                placeholder="请输入联系电话"
                                v-model="cloudSystem.contactsinfo"
                                clearable
                            >
                            </el-input>
                        </el-form-item>
                    </div>
                    <div class="item">
                        <el-form-item label="邮箱:" prop="email">
                            <el-input
                                style="width: 200px"

                                placeholder="请输入邮箱"
                                v-model="cloudSystem.email"
                                clearable
                                :rules="[
                                    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                                    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                                ]"
                            >
                            </el-input>
                        </el-form-item>
                    </div>
                </div>
                <div class="wrap">
                    <div class="item">
                        <el-form-item label="承建单位:" prop="constunit">
                            <el-input
                                style="width: 200px"

                                placeholder="请输入承建单位"
                                v-model="cloudSystem.constunit"
                                clearable
                            >
                            </el-input>
                        </el-form-item>
                    </div>
                    <div class="item">
                        <el-form-item label="承建方联系人:" prop="constcts">
                            <el-input
                                style="width: 200px"

                                placeholder="请输入承建方联系人"
                                v-model="cloudSystem.constcts"
                                clearable
                            >
                            </el-input>
                        </el-form-item>
                    </div>
                    <div class="item">
                        <el-form-item label="联系电话:" prop="constctsinfo">
                            <el-input
                                style="width: 200px"

                                placeholder="请输入联系电话"
                                v-model="cloudSystem.constctsinfo"
                                clearable
                            >
                            </el-input>
                        </el-form-item>
                    </div>
                    <div class="item">
                        <el-form-item label="邮箱:" prop="constemail">
                            <el-input
                                style="width: 200px"

                                placeholder="请输入邮箱"
                                v-model="cloudSystem.constemail"
                                clearable
                                :rules="[
                                    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                                    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                                ]"
                            >
                            </el-input>
                        </el-form-item>
                    </div>
                </div>
              <div class="wrap">
                <div class="item" v-if="false">
                  <el-form-item label="部门级别">
                    <el-select v-model="cloudSystem.deptType" clearable>
                      <el-option
                        v-for="dict in typeOptions"
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="dict.dictValue"
                      >{{dict.dictLabel}}</el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </div>
                <div class="item" style="width: calc(100% - 20px)">
                    <el-form-item
                        style="width: 100%"
                        label="项目简介:"
                        prop="introduction"
                    >
                        <el-input
                            type="textarea"
                            style="width: 100%"
                            :autosize="{ minRows: 2, maxRows: 4 }"
                            placeholder="请输入项目简介"
                            v-model="cloudSystem.introduction"
                        >
                        </el-input>
                    </el-form-item>
                </div>
            </el-form>
        </div>
        <div style="display: flex; justify-content: flex-end; margin-top: 10px">
            <el-button  type="primary" v-if="loadingTitle == '新增项目'" @click="next"
                >新增</el-button
            >
          <!--  <el-button v-if="loadingTitle == '详情'" type="primary" @click="Putnext"
                >修改</el-button
            > -->
            <el-button  @click="cancel">取 消</el-button>
        </div>
        </el-dialog>

      <!-- 用户导入对话框 -->
      <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
          <div class="el-upload__tip" slot="tip">
            <span class="el-upload__tip" style="color:red" slot="tip"> 提示：仅允许导入“xls”或“xlsx”格式文件！</span>
            <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>
</template>

<script>
import { projectListMine, DelectprojectList ,ADDproject ,detailsproject ,PUTproject, exportProject, importTemplate } from "@/api/cloud/object";
import { treeselect } from "@/api/system/dept";
import { getDicts } from "@/api/system/dict/data";
import { listUser2 } from "@/api/system/user";
import { getToken } from "@/utils/auth";

export default {
    name: "list",
    components: {},
    data() {
        return {
            loading:false,
            officeId : null,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
            },
            ADDloading: false,
            loadingTitle : '新增项目',
            // 总条数
            total: 0,
            tableData : [],

            // 新增所需变量
            //用户列表
            users: [],
            cloudSystem: {
                projectname: "", //应用系统名称
                officeId: "", //业务部门Id
                officeIdList: undefined, //业务部门Id
                officeName: "", //业务部门名称
                onlinetime: "", //上线时间
                isXc:'false', //是否新创
                contacts: "", //联系人id
                contactsNickName: "", //联系人名称
                contactsinfo: "", //联系电话
                email: "", //联系邮箱

                constunit: "", //承建单位
                constcts: "", //承建联系人姓名
                constctsinfo: "", //承建联系方式
                constemail: "", //承建邮箱

                //fundFromRadio: "", //系统建设（运维）资金来源选择
                //fundFrom: "", //系统建设（运维）资金来源  最终值
                //fundBySelf: "", //自行落实部门上云经费

                introduction: "", //项目简介
                constunit: "", //承建单位
                protectLevel : '', //等保级别
                //remarks: "", //申请理由
            },
            isIndeterminate: true,
            checkAll: false,
            rules: {
                projectname: [
                    {
                        required: true,
                        message: "请输入系统名称",
                        trigger: "blur",
                    },
                ],
                officeIdList: [
                    {
                        required: true,
                        message: "请选择业务部门",
                        trigger: "change",
                    },
                ],
                onlinetime: [
                    {
                        required: true,
                        message: "请选择上线时间",
                        trigger: "change",
                    },
                ],
                contacts: [
                    {
                        required: true,
                        message: "请选择业主方联系人",
                        trigger: "change",
                    },
                ],
                contactsinfo: [
                    {
                        validator: this.checkPhone,
                        required: true,
                        trigger: "blur",
                    },
                ],
                email: [
                    {
                        validator: this.checkEmail,
                        required: true,
                        trigger: "blur",
                    },
                ],
                constunit: [
                    {
                        required: true,
                        message: "请输入承建单位",
                        trigger: "blur",
                    },
                ],
                constcts: [
                    {
                        required: true,
                        message: "请输入承建方联系人",
                        trigger: "blur",
                    },
                ],
                constctsinfo: [
                    {
                        validator: this.checkPhone,
                        required: true,
                        trigger: "blur",
                    },
                ],
                constemail: [
                    {
                        validator: this.checkEmail,
                        required: true,
                        trigger: "blur",
                    },
                ],
                introduction: [
                    {
                        required: true,
                        message: "请输入项目简介",
                        trigger: "blur",
                    },
                ],
            },
            input2: 0,
            //部门列表树结构
            dept: [],
            // 等保
            available_domain : [] ,
            cloud_up_areaList : [],
          // 用户导入参数
          upload: {
            // 是否显示弹出层（用户导入）
            open: false,
            // 弹出层标题（用户导入）
            title: "",
            // 是否禁用上传
            isUploading: false,
            // 是否更新已经存在的用户数据
            updateSupport: 0,
            // 设置上传的请求头部
            headers: { Authorization: "Bearer " + getToken() },
            // 上传的地址
            url: process.env.VUE_APP_BASE_API + "/project/importData",
            typeOptions: [],
          },
        };
    },
    created() {
        this.getList();
        this.getListDept()
        getDicts("available_domain").then((response) => {
            this.available_domain = response.data;
        });
        getDicts("cloud_up_area").then((response) => {
            this.cloud_up_areaList = response.data;
        });
      this.getDicts("sys_office_grade").then(response => {//部门级别数据
        this.typeOptions = response.data;
      });
    },
    methods: {
        checkEmail(rule, value, callback){
            const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
            if (!value) {
            return callback(new Error('邮箱不能为空'))
            }
            setTimeout(() => {
            if (mailReg.test(value)) {
                callback()
            } else {
                callback(new Error('请输入正确的邮箱格式'))
            }
            }, 100)
        },
        checkPhone(rule, value, callback) {
            if (!value) {
            callback()
            } else {
            const reg = /^1[3|4|5|7|8|9][0-9]\d{8}$/
            if (reg.test(value)) {
                callback()
            } else {
                return callback(new Error('请输入正确的手机号'))
            }
            }
        },
        formatter(row){
            let dictLabel
            this.available_domain.forEach(item=>{
                if(item.dictValue == row.protectLevel){
                    dictLabel = item.dictLabel
                }
            })
            return dictLabel
        },
        getName(data, id) {
            data.forEach((item) => {
                if (item.id == id) {
                    this.cloudSystem.officeName = item.label;
                } else if (item.children && item.children.length) {
                    this.getName(item.children, id);
                }
            });
        },
        //业务部门变化
        deptChange(e) {
            this.users = [];
            this.cloudSystem.contacts = "";
            this.cloudSystem.officeId = "";
            if (e.length) {
                this.cloudSystem.officeId = e[e.length - 1];
                this.getName(this.dept, this.cloudSystem.officeId);
                listUser2({
                    deptId: this.cloudSystem.officeId,
                    pageNum: 1,
                    pageSize: 10000000,
                }).then((response) => {
                    this.users = response.rows;
                });
            }
        },
        /** 查询列表 */
        getList() {
            this.loading = true;
            projectListMine(this.queryParams)
                .then((response) => {
                    this.tableData = response.rows;
                    this.total = response.total;
                    this.loading = false;
                })
                .then(() => {});
        },
        /** 查询详情 */
        showDetail(id) {
            this.$router.push("/clouds/CloudSystemDetails/" + id);
        },
        //部门列表
        getListDept() {
            treeselect({}).then((response) => {
                this.dept = response.data;
            });
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.queryParams.projectname = ''
            // this.resetForm("queryForm");
            this.handleQuery();
        },
        //新增弹窗
        showAdd(id) {
            if(!id){
                this.loadingTitle = '新增项目'
                this.ADDloading = true
                this.ResetForm()
            }else{
                this.loadingTitle = '详情'
                detailsproject(id).then(res=>{
                    let officeId = Number(res.data.officeId)
                    this.users = [];
                    this.cloudSystem.contacts = "";
                        listUser2({
                            deptId: officeId,
                            pageNum: 1,
                            pageSize: 10000000,
                        }).then((response) => {
                            this.users = response.rows;
                            this.cloudSystem = res.data
                            this.cloudSystem.isXc = res.data.isXc + ''
                            this.cloudSystem.officeId = Number(res.data.officeId)
                            this.cloudSystem.officeIdList = Number(res.data.officeId)
                            this.ADDloading = true
                        });

                })
            }
        },
        // 删除项目
        del(id){
            this.$confirm("是否确认删除该项目?", "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                DelectprojectList(id).then(res=>{
                    this.$message({
                        message: res.msg,
                        type: "success",
                    });
                    this.getList();
                })
            })
        },
        ResetForm(){
            this.cloudSystem = {
                projectname: "", //应用系统名称
                officeId: null, //业务部门Id
                officeName: "", //业务部门名称
                onlinetime: "", //上线时间
                isXc:'false',
                contacts: null, //联系人id
                contactsNickName: "", //联系人名称
                contactsinfo: "", //联系电话
                email: "", //联系邮箱

                constunit: "", //承建单位
                constcts: "", //承建联系人姓名
                constctsinfo: "", //承建联系方式
                constemail: "", //承建邮箱

                //fundFromRadio: "", //系统建设（运维）资金来源选择
                //fundFrom: "", //系统建设（运维）资金来源  最终值
                //fundBySelf: "", //自行落实部门上云经费

                introduction: "", //项目简介
                constunit: "", //承建单位
                protectLevel : '', //等保级别
                //remarks: "", //申请理由
            }
        },
        cancel(){
            this.getList();
            this.ADDloading = false
        },
        next() {
            this.$refs.cloudSystem.validate((valid) => {
                if (valid) {
                    this.users.some((item) => {
                        if (item.userId == this.cloudSystem.contacts) {
                            this.cloudSystem.contactsNickName = item.nickName;
                            return true;
                        }
                    });
                    this.$confirm("是否确认提交?", "警告", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                    }).then(() => {
                        ADDproject(this.cloudSystem)
                            .then((res) => {
                                this.$message({
                                    message: res.msg,
                                    type: "success",
                                });
                                this.cancel()
                            })
                            .finally(() => {
                            });
                    });
                } else {
                    return false;
                }
            });
        },
        Putnext() {
            this.$refs.cloudSystem.validate((valid) => {
                if(valid){
                    this.users.some((item) => {
                        if (item.userId == this.cloudSystem.contacts) {
                            this.cloudSystem.contactsNickName = item.nickName;
                            return true;
                        }
                    });
                    this.$confirm("是否修改项目?", "警告", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                    }).then(() => {
                        PUTproject(this.cloudSystem)
                            .then((res) => {
                                this.$message({
                                    message: res.msg,
                                    type: "success",
                                });
                                this.cancel()
                            })
                            .finally(() => {
                            });
                    });
                }else{
                    return
                }
            });
        },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm("是否确认导出所有项目?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            return exportProject(queryParams);
          })
          .then((response) => {
            this.download(response.msg);
          });
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "项目导入";
        this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
        importTemplate().then(response => {
          this.download(response.msg);
        });
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      typeFormat(row, column) {
        return this.selectDictLabel(this.typeOptions, row.type);
      },
    },
};
</script>
<style scoped lang="less">
.el-table{
    color: #000;
}
.el-form--inline .el-form-item {
    vertical-align: revert;
}

.el-step__description {
    margin: 5px 0 14px 0 !important;
}
    .title {
            text-align: left;
            margin-bottom: 20px;
            font-size: 16px;
            font-weight: bold;
            padding-left: 4px;
            border-left: 4px solid #38b3aa;
        }

    .msg {
        padding: 0 20px 20px 0px;
        background: #faf9ff;
        display: flex;
        flex-wrap: wrap;
        border-radius: 10px;
        .wrap {
            width: 100%;
            display: flex;
            flex-wrap: wrap;
        }

        .item {
            margin-left: 20px;
            width: calc(25% - 20px);
            min-width: 340px;
            display: flex;
        }
    }
</style>
